<script lang="ts" setup>
import { onMounted, ref, useTemplateRef } from 'vue';
import { ElTree, ElCheckbox, ElCheckboxGroup } from 'element-plus';
import { getMenuTreeApi, roleBindMenuApi } from '@/api';
import type { UserMenuAuth } from '@/store';
import { BasicButton, BasicPage } from '@/components/Basic';
import { $t } from '@/locales';
import analyticsTrends from './charts/analytics-trends.vue';

defineOptions({
  name: 'Dashboard',
});

type MenuPermsType = Record<string, string[]>;

const elTreeRef = useTemplateRef('elTreeRef');

/**
 * 获取treeData
 */
const treeData = ref([]);
onMounted(async () => {
  treeData.value = await getMenuTreeApi();
});

const params = ref<MenuPermsType>({});
const handleGetCheckedVal = async () => {
  params.value = {};
  const menuIds = elTreeRef.value?.getCheckedKeys() ?? [];
  for (const menuId of menuIds) {
    params.value[menuId] = checkedMap.value[menuId];
  }
  await roleBindMenuApi({
    id: 'sdf',
    perms: params.value,
  });
};
const handleSetCheckedVal = () => {
  checkedMap.value = {
    'b19d5b6e-48fe-4443-aa2d-9fc94abb3813': [
      '7f9b0dee-2003-49c3-bb34-3813c54d3331',
    ],
    'ac4422d2-8f93-4750-b8f7-21fbc5bc008b': [],
  };
  elTreeRef.value?.setCheckedKeys([
    'b19d5b6e-48fe-4443-aa2d-9fc94abb3813',
    'ac4422d2-8f93-4750-b8f7-21fbc5bc008b',
  ]);
};

// 点击复选框节点: 全选/取消节点下的按钮权限
const checkedMap = ref<MenuPermsType>({});
const handleCheckChange = (
  _: UserMenuAuth,
  { checkedNodes }: { checkedNodes: UserMenuAuth[] },
) => {
  checkedMap.value = {};
  checkedNodes.forEach((el) => {
    checkedMap.value[el.id] = el.buttons.map((item) => item.id);
  });
};
</script>
<template>
  <BasicPage auto-content-height>
    <div class="flex">
      <span>菜单权限</span>
      <span class="ml-[25%] block">按钮权限</span>
    </div>
    <ElTree
      :data="treeData"
      node-key="id"
      show-checkbox
      default-expand-all
      ref="elTreeRef"
      @check="handleCheckChange"
    >
      <template #default="{ data }">
        <span>{{ $t(data.title) }}</span>
        <ElCheckboxGroup
          v-model="checkedMap[data.id]"
          class="ml-48"
          @click.stop
        >
          <ElCheckbox
            v-for="item in data.buttons"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </ElCheckboxGroup>
      </template>
    </ElTree>
    <BasicButton @click="handleGetCheckedVal">获取</BasicButton>
    <BasicButton @click="handleSetCheckedVal">设置</BasicButton>
    <div>原始数据：{{ checkedMap }}</div>
    <div>要传递的数据：{{ params }}</div>
    <analyticsTrends />
  </BasicPage>
</template>
<style scoped lang="scss"></style>
